package org.example.controller.platform;

import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.example.common.result.Result;
import org.example.entity.User;
import org.example.service.SmsService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 平台端 短信验证码控制器
 * 
 * 提供两种验证码发送方式：
 * 1. /send - 登录验证码：需要手机号已注册且为平台端账号
 * 2. /send/change-phone - 修改手机号验证码：新手机号无需已注册
 */
@RestController
@RequestMapping("/sms/platform")
@Slf4j
@Component("platformSmsController")
@Tag(name = "平台端-短信验证码", description = "平台端短信验证码相关接口")
public class SmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    /**
     * 发送验证码（平台端，仅已录入且启用的平台账号可发）
     */
    @PostMapping("/send")
    @io.swagger.v3.oas.annotations.Operation(
        summary = "平台端-发送登录验证码",
        description = "为已注册的平台端账号发送登录验证码，需要手机号已注册且为平台端账号"
    )
    public Result<Map<String, Object>> sendVerificationCode(@RequestBody Map<String, String> request) {
        try {
            String phone = request.get("phone");
            if (phone == null || phone.trim().isEmpty()) {
                return Result.badRequest("手机号不能为空");
            }

            // 平台账号校验：存在 + 平台端 + 启用（可按需增加 is_platform_admin 限制）
            User user = userService.getByPhoneAndUserType(phone, "平台端");
            if (user == null) {
                return Result.badRequest("手机号未注册平台账号");
            }
            if (user.getStatus() == null || user.getStatus() != 1) {
                return Result.badRequest("账号未启用，无法发送验证码");
            }
            // 如需仅限平台后台账号，放开下一行
            // if (user.getIsPlatformAdmin() == null || user.getIsPlatformAdmin() != 1) return Result.badRequest("不是平台后台账号");

            boolean success = smsService.sendLoginCode(phone, "平台端");
            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("phone", phone);
                data.put("expiresIn", 300);
                return Result.success("验证码发送成功", data);
            } else {
                return Result.error("验证码发送失败");
            }
        } catch (Exception e) {
            log.error("发送验证码失败: {}", request, e);
            return Result.error("验证码发送失败: " + e.getMessage());
        }
    }

    /**
     * 发送修改手机号验证码（平台端，新手机号无需已注册）
     */
    @PostMapping("/send/change-phone")
    @io.swagger.v3.oas.annotations.Operation(
        summary = "平台端-发送修改手机号验证码",
        description = "为新手机号发送验证码，用于修改手机号场景，无需已注册"
    )
    public Result<Map<String, Object>> sendChangePhoneCode(@RequestBody Map<String, String> request) {
        try {
            String phone = request.get("phone");
            if (phone == null || phone.trim().isEmpty()) {
                return Result.badRequest("手机号不能为空");
            }

            // 修改手机号场景：新手机号无需已注册，直接发送验证码
            boolean success = smsService.sendLoginCode(phone, "平台端");
            if (success) {
                Map<String, Object> data = new HashMap<>();
                data.put("phone", phone);
                data.put("expiresIn", 300);
                return Result.success("验证码发送成功", data);
            } else {
                return Result.error("验证码发送失败");
            }
        } catch (Exception e) {
            log.error("发送修改手机号验证码失败: {}", request, e);
            return Result.error("验证码发送失败: " + e.getMessage());
        }
    }
}
